// config

var app =
    angular.module('app')
        .config(
        ['$controllerProvider', '$compileProvider', '$filterProvider', '$provide',
            function ($controllerProvider, $compileProvider, $filterProvider, $provide) {

                // lazy controller, directive and service
                app.controller = $controllerProvider.register;
                app.directive = $compileProvider.directive;
                app.filter = $filterProvider.register;
                app.factory = $provide.factory;
                app.service = $provide.service;
                app.constant = $provide.constant;
                app.value = $provide.value;
            }
        ])
        .config(['$translateProvider', function ($translateProvider) {
            // Register a loader for the static files
            // So, the module will search missing translation tables under the specified urls.
            // Those urls are [prefix][langKey][suffix].
            $translateProvider.useStaticFilesLoader({
                prefix: 'l10n/',
                suffix: '.js'
            });
            // Tell the module what language to use by default
            $translateProvider.preferredLanguage('zh_CN');
            // Tell the module to store the language in the local storage
            $translateProvider.useLocalStorage();
        }]);

app.run(['$rootScope', '$log', 'UserInfo', '$state', function($rootScope, $log, UserInfo, $state){
    $rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){
        $log.debug('successfully changed states') ;
        $log.debug('event', event);
        $log.debug('toState', toState);
        $log.debug('toParams', toParams);
        $log.debug('fromState', fromState);
        $log.debug('fromParams', fromParams);
    });

    $rootScope.$on('$stateNotFound', function(event, unfoundState, fromState, fromParams){
        $log.error('The request state was not found: ' + unfoundState);
    });

    $rootScope.$on('$stateChangeError', function(event, toState, toParams, fromState, fromParams, error){
        $log.error('An error occurred while changing states: ' + error);
        $log.debug('event', event);
        $log.debug('toState', toState);
        $log.debug('toParams', toParams);
        $log.debug('fromState', fromState);
        $log.debug('fromParams', fromParams);
    });

    $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){
        $log.debug('event', event);
        $log.debug('toState', toState);
        $log.debug('toParams', toParams);
        $log.debug('fromState', fromState);
        $log.debug('fromParams', fromParams);

        if(top.window.jsVersion) {
        	var url = toState.templateUrl;
        	var sub = '_dc=' + top.window.jsVersion;
        	if(url.indexOf(sub) === -1) {
        		if (url.indexOf('?') >= 0) {
                    if (url.substring(0, url.length - 1) === '&') {
                    } else {
                    	url += '&';
                    }
                } else {
                	url += '?';
                }
        		url += sub;
        	}
        	toState.templateUrl = url;
        }
        // 不是 access 开始的路由，这部分不需要登录后跳转
        var fdStart = toState.name.indexOf("access");
        if(fdStart == 0){
        } else {
            $rootScope.cacheUrlState = {};
            $rootScope.cacheUrlState.toState = toState;
            $rootScope.cacheUrlState.toParams = toParams;
        }

        // 权限判断
        var hasAuth = UserInfo.isAuthorizedForState(toState);
        if(!hasAuth) {
        	event.preventDefault();
        	if(UserInfo.isNeedLogin(toState)){
        		 $state.go('access.login', null, {reload : true});
        	} else {
        		$rootScope.needLogin = true;
        		$state.go('access.denied', null, {reload : true});
        	}
        }

    });
}]);

app.factory('myInterceptor', ['$q','$rootScope', '$injector', '$location', '$templateCache', function ($q, $rootScope, $injector, $location, $templateCache) {
    var responseInterceptor = {
        'response' : function(config) {
            var $state = $injector.get('$state');
            if (config.status == '200' && (config.data.status == 600)) {
                /**
                 * 600 未登录 或则是会话失效
                 *
                 */
                $rootScope.needLogin = true;
                // $rootScope.absUrl = $location.absUrl();
                //if(angular.isDefined($rootScope.cacheUrlState) && angular.isDefined($rootScope.cacheUrlState.toState)) {
                //}

                $rootScope.cleanUserInfo();
                if(angular.isDefined($rootScope.cacheUrlState) && angular.isDefined($rootScope.cacheUrlState.toState)) {
                    $templateCache.remove($rootScope.cacheUrlState.toState.templateUrl);
                }
                $templateCache.remove('tpl/app.html');
                $state.go('app.home', null, {reload : true});
                return config;
            } else if (config.status == '200' && (config.data.status == 401)) {
                /**
                 * 401
                 * 未鉴权，需要重新登录
                 *
                 */
                $rootScope.needLogin = true;
                // $rootScope.absUrl = $location.absUrl();
                //if(angular.isDefined($rootScope.cacheUrlState) && angular.isDefined($rootScope.cacheUrlState.toState)) {
                //}

                if(angular.isDefined($rootScope.cacheUrlState) && angular.isDefined($rootScope.cacheUrlState.toState)) {
                    $templateCache.remove($rootScope.cacheUrlState.toState.templateUrl);
                }
                $templateCache.remove('tpl/app.html');
                $state.go('access.login', null, {reload : true});
                return config;
            } else if (config.status == '200' && config.data.status == 403){
                /**
                 * 禁止访问
                 */

                $rootScope.needLogin = true;
                // $rootScope.absUrl = $location.absUrl();
                //if(angular.isDefined($rootScope.cacheUrlState) && angular.isDefined($rootScope.cacheUrlState.toState)) {
                //}

                $templateCache.remove($rootScope.cacheUrlState.toState.templateUrl);
                $templateCache.remove('tpl/app.html');
                $state.go('access.denied', null, {reload : true});
                return config;
            }

            // application/json
            if(config.config.headers && config.config.headers.Accept.indexOf('application/json') > -1 && config.data && typeof(config.data) == 'object') {
                config.data = FastJson.format(config.data);
            }
            return config;
        }
    };
    return responseInterceptor;
}]);
app.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.interceptors.push('myInterceptor');
}]);